<!--
 * @Description:用户管理页面
-->
<template>
  <BaseMainSlot>
    <template v-slot:btnsBar>
      <ActionBar
        :page-no="174"
        :add-active="addActive"
        :edit-active="editActive"
        :cancel-active="cancelActive"
        :save-active="saveActive"
        :func-auth-active="funcAuthActive"
        :func-app-auth-active="funcAppAuthActive"
        :assign-role="assignRoleActive"
        :has-func-auth="true"
        :has-app-auth="true"
        :has-assign-role="true"
        :has-del="false"
        @funcAuth="funcAuthShow"
        @funcAppAuth="funcAppAuthShow"
        @assignRole="assignRoleShow('formData')"
        @add="add"
        @cancel="cancel"
        @edit="edit"
        @save="save('formData')"
      />
    </template>
    <template v-slot:searchbox>
      <el-collapse v-model="activeName" accordion @change="handleChange">
        <el-collapse-item name="1">
          <template slot="title">
            <div class="select-btns table-btns" @click.stop="changeSelect()">
              <i class="el-icon-circle-check"></i>
              <p v-if="activeName==='1'">收起筛选</p>
              <p v-if="activeName===''">展开筛选</p>
            </div>
          </template>
          <div class="select-box-content">
            <div class="select-box-content-name">用户姓名：</div>
            <el-input v-model="username" clearable placeholder="请输入用户姓名" @change="queryPageList()" />
          </div>
        </el-collapse-item>
      </el-collapse>
    </template>
    <template v-slot:content>
      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        border
        height="calc(100% - 50px)"
        @row-click="handleEdit"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="50">
          <template slot-scope="scoped">
            {{ scoped.row.userId?scoped.$index+1:'' }}
          </template>
        </el-table-column>
        <el-table-column prop="nickname" label="昵称" />
        <el-table-column prop="username" label="账号" />
        <el-table-column width="200" label="操作">
          <template v-if="scoped.row.personNo" slot-scope="scoped">
            <div class="table-btns-box">
              <div class="table-btns edit-btns" @click="edit(scoped.row)" v-if="judgePermission(174,'edit')">
                <i class="el-icon-edit-outline"></i>
                <p>修改</p>
              </div>
              <div class="table-btns del-btns" @click="assignRoleShow(scoped.row)"  v-if="judgePermission(174,'role')">
                <i class="el-icon-delete"></i>
                <p>分配角色</p>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column width="80" label="状态">
          <template v-if="scope.row.personNo" slot-scope="scope">
            <el-switch
              v-model="scope.row.expire"
              :active-value="'启用'"
              :inactive-value="'禁用'"
              :disabled="judgePermission(174, 'start')"
              @change="faciStatus(scope.row)"
            />
          </template>
        </el-table-column>
      </el-table>
      <Pagination
        :page-size="pageSize"
        :current-page="currentPage"
        :total-size="totalSize"
        @changePageSize="changePageSize"
        @changeCurrentPage="changeCurrentPage"
      />
      <div class="dialog">
      <el-dialog
        :title="titleText + '用户信息'"
        :visible.sync="dialogFormVisible"
        :before-close="cancel"
        width="40%"
        :close-on-click-modal="false"
        top="0"
      >
        <el-form
          ref="formData"
          label-position="left"
          :model="formData"
          :rules="rules"
          class="el-form"
        >
          <el-form-item label="员工:" prop="personNo" class="w100p">
            <el-select
              v-model="formData.personNo"
              filterable
              clearable
              @change="staffPerson"
            >
              <el-option
                v-for="(item, index) in staffData"
                :key="index"
                :label="item.person.name"
                :value="item.personNo"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="用户名:" prop="nickname" class="w100p">
            <el-input v-model="formData.nickname" clearable />
          </el-form-item>
          <el-form-item label="账号:" prop="username" class="w100p">
            <el-input v-model="formData.username" clearable />
          </el-form-item>
          <el-form-item
            v-if="nowChanceStau === 'add'"
            :label="'密码:'"
            prop="password"
            class="w100p"
          >
            <el-input
              v-model="formData.password"
              show-password
              type="password"
              autocomplete="off"
              clearable
            />
          </el-form-item>
          <el-form-item
            v-if="nowChanceStau === 'edit'"
            :label="'旧密码:'"
            prop="oldPassword"
            class="w100p"
          >
            <el-input
              v-model="formData.oldPassword"
              show-password
              type="password"
              clearable
              autocomplete="off"
            />
          </el-form-item>
          <el-form-item
            v-if="nowChanceStau === 'edit' && formData.oldPassword"
            label="新密码:"
            prop="newPassword"
            class="w100p"
          >
            <el-input
              v-model="formData.newPassword"
              show-password
              type="password"
              clearable
            />
          </el-form-item>
          <el-form-item
            v-if="nowChanceStau === 'edit' && formData.oldPassword"
            label="确认密码"
            prop="newPasswords"
            class="w100p"
          >
            <el-input
              v-model="formData.newPasswords"
              type="password"
              autocomplete="off"
            />
          </el-form-item>
          <el-form-item
            v-if="!formData.personNo"
            label="姓名:"
            prop="name"
            class="w100p"
          >
            <el-input
              v-model="formData.name"
              placeholder="请输入员工姓名"
              clearable
            />
          </el-form-item>
          <el-form-item
            v-if="!formData.personNo"
            label="性别:"
            prop="gender"
            class="w100p"
          >
            <el-select v-model="formData.gender" filterable clearable>
              <el-option label="男" value="男" />
              <el-option label="女" value="女" />
            </el-select>
          </el-form-item>
          <el-form-item
            v-if="!formData.personNo"
            label="身份证号:"
            prop="identificationNumber"
            class="w100p"
          >
            <el-input
              v-model="formData.identificationNumber"
              placeholder="身份证号"
            />
          </el-form-item>
          <el-form-item
            v-if="!formData.personNo"
            label="手机号:"
            prop="phone"
            class="w100p"
          >
            <el-input
              v-model="formData.phone"
              placeholder="请输入手机号"
              clearable
            />
          </el-form-item>
          <el-form-item
            v-if="!formData.personNo"
            label="座机号:"
            prop="landline"
            class="w100p"
          >
            <el-input
              v-model="formData.landline"
              placeholder="请输入座机号"
              clearable
            />
          </el-form-item>
          <el-form-item
            v-if="!formData.personNo"
            label="邮箱:"
            prop="email"
            class="w100p"
          >
            <el-input
              v-model="formData.email"
              type="email"
              placeholder="请输入邮箱"
              clearable
            />
          </el-form-item>
          <el-form-item
            v-if="!formData.personNo"
            label="微信:"
            prop="weChat"
            class="w100p"
          >
            <el-input
              v-model="formData.weChat"
              placeholder="请输入微信"
              clearable
            />
          </el-form-item>
          <el-form-item
            v-if="!formData.personNo"
            label="住址:"
            prop="address"
            class="w100p"
          >
            <el-input
              v-model="formData.address"
              placeholder="请输入住址"
              clearable
            />
          </el-form-item>
          <el-form-item
            v-if="!formData.personNo"
            label="生日:"
            prop="birthday"
            class="w100p"
          >
            <el-date-picker
              v-model="formData.birthday"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="请选择生日日期"
              clearable
              filterable
            />
          </el-form-item>
        </el-form>
        <div v-if="nowChanceStau !== ''" slot="footer" class="dialog-footer">
          <el-button class="cancelbtn" @click="cancel"> 取 消 </el-button>
          <el-button
            class="savebtn"
            type="primary"
            @click="save('formData')"
          >
            保 存
          </el-button>
        </div>
      </el-dialog>
      <el-dialog
        title="分配角色"
        :visible.sync="dialogFormAssignVisible"
        :before-close="cancelAssign"
        width="40%"
        top="0"
        :close-on-click-modal="false"
      >
        <assignroleComponent
          v-if="dialogFormAssignVisible"
          ref="assignrole"
          :username="formData.username"
          :userstu="userstu"
          @users="users"
        />
        <div slot="footer" class="dialog-footer">
          <el-button
            class="cancelbtn"
            @click="dialogFormAssignVisible = false"
          >
            取 消
          </el-button>
          <el-button
            class="savebtn"
            type="primary"
            @click="userAdd('formData')"
          >
            保 存
          </el-button>
        </div>
      </el-dialog>
      <el-dialog
        title="功能权限"
        :visible.sync="dialogFormFuthDataVisible"
        :before-close="cancelAssign"
        width="40%"
        :close-on-click-modal="false"
        top="0"
      >
        <DataAuthComponent
          v-if="dialogFormFuthDataVisible"
          ref="assignrole"
          :username="formData.username"
          :userstu="userstu"
          @users="users"
        />
        <div slot="footer" class="dialog-footer">
          <el-button
            class="cancelbtn"
            @click="dialogFormFuthDataVisible = false"
          >
            取 消
          </el-button>
          <el-button
            class="savebtn"
            type="primary"
            @click="userAdd"
          >
            保 存
          </el-button>
        </div>
      </el-dialog>
      <el-dialog
        title="分配App功能权限"
        :visible.sync="dialogDataAppAuthFormVisible"
        width="40%"
        :close-on-click-modal="false"
        top="0"
      >
        <DataAppAuthComponent
          v-if="dialogDataAppAuthFormVisible"
          ref="funcAuth"
          :username="formData.username"
          :userstu="userstu"
          @users="users"
        />
        <div slot="footer" class="dialog-footer">
          <el-button class="cancelbtn" @click="cancel">
            取 消
          </el-button>
          <el-button
            class="savebtn"
            type="primary"
            @click="userAdd('formData')"
          >
            保 存
          </el-button>
        </div>
      </el-dialog>
      </div>
    </template>
  </BaseMainSlot>
</template>

<script>
import ActionBar from "@/components/ActionBar";
import Pagination from "@/components/Pagination";
import userManage from "@/api/system-settings/user-manage";
import assignroleComponent from "../components/assign-rolle-component";
import DataAuthComponent from "../components/func-auth-user-component";
import DataAppAuthComponent from "../components/App-user-component";
import BaseMainSlot from "@/components/BaseMainSlot/kong";
import axios from "axios";
import { getToken } from "@/utils/auth";

import { mymixin } from "@/utils/mixins";
import { mapGetters } from 'vuex';
export default {
  name: "",
  components: {
    BaseMainSlot,
    ActionBar,
    Pagination,
    DataAuthComponent,
    assignroleComponent,
    DataAppAuthComponent
  },
  mixins: [mymixin],
  data () {
    var checkIdentitytionId = (rule, value, callback) => {
      const reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
      if (value === "" || value === undefined || value === null) {
        callback();
      } else {
        if (!reg.test(value) && value !== "") {
          callback(new Error("请输入正确的身份证号码"));
        } else {
          callback();
        }
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.formData.newPassword) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      // 右侧权限展示1主界面,2功能权限,3数据权限,4分配角色
      nowpage: 1,
      // 操作按钮的逻辑及展示数据
      addActive: true,
      editActive: false,
      delActive: false,
      saveActive: false,
      cancelActive: false,
      funcAuthActive: false,
      // 数据权限
      dataAuthActive: false,
      // 分配角色
      assignRoleActive: false,
      funcAppAuthActive: false,
      dialogDataAppAuthFormVisible: false,
      // table
      loading: true,
      // 当前页
      currentPage: 1,
      // 每页的数据条数
      pageSize: 10,
      // 总条数
      totalSize: 0,
      // 员工姓名
      username: "",
      // 是否能输入
      canInput: false,
      tableData: [],
      formData: {},
      rules: {
        username: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        account: [{ required: true, message: "请输入用户名", trigger: "blur" }],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 16,
            message: "长度在 6 到 16 个字符",
            trigger: "blur"
          }
        ],
        newPassword: [
          { required: true, message: "请输入新密码", trigger: "blur" },
          {
            min: 6,
            max: 16,
            message: "长度在 6 到 16 个字符",
            trigger: "blur"
          }
        ],
        newPasswords: [
          { required: true, message: "请再次输入密码", trigger: "blur" },
          {
            validator: validatePass2,
            trigger: "blur"
          }
        ],
        gender: [{ required: true, message: "请选择性别", trigger: "blur" }],
        name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        identificationNumber: [
          { required: true, message: "请输入身份证", trigger: "blur" },
          { validator: checkIdentitytionId, trigger: "blur" }
        ],
        phone: [
          { required: true, message: "请输入联系方式", trigger: "blur" },
          {
            pattern: /^((0\d{2,3}-\d{7,8})|(1[3584]\d{9}))$/,
            message: "请输入合法手机号/电话号",
            trigger: "blur"
          }
        ]
      },
      // 选中的数据项数组 employeeId组成 (此数组最多为一个)
      selectedStaffList: [],
      dialogTitle: "",
      dialogFormVisible: false,
      dialogFormAssignVisible: false,
      dialogFormFuthDataVisible: false,
      staffData: [],
      userstu: ""
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission"
    })
  },
  watch: {},
  created() {
    // 获取表格数据
    this.getTableDataList();
    this.selectData();
  },
  mounted() {},
  methods: {
    userAdd() {
      // console.log(this.formData)
      this.userstu = "add";
    },
    users() {
      this.userstu = "";
      this.dialogFormAssignVisible = false;
      this.dialogFormFuthDataVisible = false;
      this.dialogDataAppAuthFormVisible = false
    },
    // 获取下拉框数据
    async selectData() {
      // const { data: resStaff } = await personManage.getStaffListByCondition({});
      // this.staffData = resStaff;
    },
    staffPerson(e) {
      if (!e) {
        this.$set(this.formData, "personNo", undefined);
      }
    },
    getTableDataList() {
      this.loading = true;
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        entity: {
          organizationNo: sessionStorage.organizationNo,
          username: this.username
        }
      };
      userManage.getUserStaffList(params).then((res) => {
        this.loading = false;
        if(res.code===1){
            let data = res.data||[];
        // 赋值总条数
        this.totalSize = data.totalElements||0;
        // 赋值数组
        this.tableData = data.content||[];
        this.addblankmet();
        this.resetActionBar();
        }
      });
    },
    // 填充表格空白行
    addblankmet() {
      let havline = this.tableData.length % this.pageSize;
      if (this.tableData.length < this.pageSize) {
        if (havline < this.pageSize) {
          const remain = this.pageSize - havline;
          for (var i = 0; i < remain; i++) {
            this.tableData.push({ indflag: i + this.tableData.length - 1 });
          }
        }
      }
    },
    // 初始化操作栏状态
    resetActionBar() {
      this.nowChanceStau = "";
      this.addActive = true;
      this.editActive = false;
      this.delActive = false;
      this.saveActive = false;
      this.funcAuthActive = false;
      this.dataAuthActive = false;
      this.assignRoleActive = false;
      this.cancelActive = false;
      this.canInput = false;
      this.formData = {};
      this.dialogFormAssignVisible = false;
      this.funcAppAuthActive = false
      this.dialogFormFuthDataVisible = false;
      this.dialogDataAppAuthFormVisible = false
    },
    search() {
      this.currentPage = 1;
      this.getTableDataList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.getTableDataList();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.getTableDataList();
    },
    handleEdit(row) {
      this.formData = JSON.parse(JSON.stringify(row));
      if (row.personNo) {
        this.funcAuthActive = true;
        this.funcAppAuthActive = true;
        this.assignRoleActive = true;
      } else {
        this.resetActionBar();
      }
      // this.openDialog("edit");
    },
    handleSelectionChange(list) {
      this.selectedStaffList = [];
      this.selectedStaffList = list.map((item) => item.employeeId);
      if (this.selectedStaffList.length > 0) this.delActive = true;
      else this.delActive = false;

      // 多个处理为单个数据
      if (this.selectedStaffList.length > 1) {
        this.$message.warning("员工不可多选删除！");
        this.selectedStaffList.splice(0, this.selectedStaffList.length - 1);
        console.log(this.selectedStaffList);
      }
    },
    faciStatus(e) {
      this.$confirm("是否禁用", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass"
      })
        .then(() => {
          let params = {
            ...e
          };
          // console.log(e)
          // if (e.expire === '启用') {
          //   params.expire = '禁用'
          // } else if (e.expire === '禁用') {
          //   this.$set(params, "expire", '启用')
          // }
          // // this.formData.topOrganization = sessionStorage.topOrganization;
          // // this.formData.organizationNo = [sessionStorage.organizationNo];
          // console.log(params)
          userManage.editUserInfo(params).then((res) => {
            if (res.code === 1) {
              this.$message.success("修改成功！");
              this.closeDialog();
              this.resetActionBar();
              this.getTableDataList();
            }
          });
          this.$nextTick(() => {
            setTimeout(() => {
              this.getTableDataList();
            }, 300);
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
          this.getTableDataList();
          // this.resetActionBar();
        });
    },
    // 点击功能权限触发的方法
    funcAuthShow() {
      this.nowpage = 2;
      this.cancelActive = true;
      this.addActive = false;
      this.editActive = false;
      // console.log("点击了功能权限");
      this.dialogFormFuthDataVisible = true;
      this.saveActive = true;
    },
    // 点击数据权限触发的方法
    dataAuthShow() {
      this.nowpage = 3;
      this.cancelActive = true;
      this.addActive = false;
      this.editActive = false;
      console.log("点击了数据权限");
      this.saveActive = true;
    },
    // 点击了分配角色
    assignRoleShow(data) {
      // this.nowpage = 4;
      this.dialogFormAssignVisible = true;
      // this.formData = data;
    },
    funcAppAuthShow() {
      this.dialogDataAppAuthFormVisible = true
    },
    cancel() {
      this.closeDialog();
      this.formData = {};
      this.funcAuthActive = false;
      this.dataAuthActive = false;
      this.assignUserActive = false;
      this.funcAuthActive = false;
      this.funcAppAuthActive = false;
      this.addActive = true;
      this.dialogFormAssignVisible = false;
      this.dialogFormFuthDataVisible = false;
      this.dialogDataAppAuthFormVisible = false
      // this.$nextTick(() => {
      this.dialogFormAssignVisible = false;
      this.dialogFormFuthDataVisible = false;
      this.dialogDataAppAuthFormVisible = false
      //   if (this.formData) {
      //     this.$refs[formData].resetFields();
      //   }
      // })
    },
    del() {
      this.$message.warning("用户不允许删除");
      // userManage
      //   .delInspectionRouteInfo(this.inspectionRouteIdList)
      //   .then(res => {
      //     if (res.code === 1) {
      //       this.$message.success(res.msg);
      //       this.getTableDataList();
      //     }
      //   });
    },
    cancelAssign() {
      this.closeDialog();
    },
    save(formData) {
      if (!formData) return;
      this.$refs[formData].validate(async (valid) => {
        if (valid) {
          if (this.nowChanceStau === "edit" && this.nowpage === 1) {
            // this.formData.organizationNo = [sessionStorage.organizationNo];
            // this.formData.topOrganization = sessionStorage.topOrganization;
            // console.log(this.formData.oldPassword)
            if (this.formData.oldPassword !== undefined && this.formData.oldPassword !== '') {
              await this.editPass();
            }
            // return
            userManage.editUserInfo(this.formData).then((res) => {
              if (res.code === 1) {
                this.$message.success("修改成功！");
                this.closeDialog();
                this.resetActionBar();
                this.getTableDataList();
              }
            });
          } else if (this.nowChanceStau === "add" && this.nowpage === 1) {
            // 新增接口
            if (!this.formData.personNo) {
              let from = JSON.parse(JSON.stringify(this.formData));
              // this.$set(this.formData)
              this.formData = {
                person: {
                  ...from
                },
                nickname: from.nickname,
                username: from.username,
                password: from.password
              };
            }
            this.formData.organizationNo = [sessionStorage.organizationNo];
            this.formData.topOrganization = sessionStorage.topOrganization;
            this.formData.expire = "启用";
            // return
            this.registerIofo(this.formData);
          }
        } else {
          // console.log('error submit!!');
          return false;
        }
      });
    },
    // 修改密码
    editPass() {
      let zhurl = this.$baseurl.webServiceUrl + "v3/virtualSystem/v1/user/resetPassword";
      let data = `username=${this.formData.username}&oldPassword=${this.formData.oldPassword}&newPassword=${this.formData.newPassword}`
      axios({
        method: "POST",
        url: zhurl,
        headers: {
          databaseName: getToken("databaseName"),
          accessToken: getToken("token"),
          organizationList: getToken("organizationList"),
          organizationNo: getToken("organizationNo"),
          virtualSystemNo: getToken("virtualSystemNo")
        },
        data: data
      }).then((res) => {
        if (res.data.code === 1) {
          this.getTableDataList();
          this.$message.success("密码修改成功");
        } else {
          if (res.data.msg === '原密码错误') {
            this.$message.warning("原密码错误");
          } else {
            this.$message.warning("密码修改失败");
          }
        }
      });
    },
    registerIofo(params, sysDataBaseName) {
      let zhurl = this.$baseurl.webServiceUrl + "v3/virtualSystem/v1/user/add";
      axios({
        method: "POST",
        url: zhurl,
        headers: {
          databaseName: getToken("databaseName"),
          accessToken: getToken("token"),
          organizationList: getToken("organizationList"),
          organizationNo: getToken("organizationNo"),
          virtualSystemNo: getToken("virtualSystemNo")
        },
        data: {
          ...params
        }
      }).then((res) => {
        if (res.data.code === 1) {
          this.closeDialog();
          this.getTableDataList();
          this.$message.success("添加成功");
        } else {
          this.$message.warning("添加失败");
        }
      });
    },
    openDialog(type) {
      this.dialogFormVisible = true;
      this.dialogTitle = type === "add" ? "新增" : "编辑";
      this.nowChanceStau = type;
    },
    closeDialog() {
      this.dialogFormVisible = false;
      this.dialogFormAssignVisible = false;
      this.dialogDataAppAuthFormVisible = false;
      this.dialogTitle = null;
      this.addActive = true;
      this.nowChanceStau = "";
    }
  }
};
</script>

<style scoped lang="scss">
@import "~@/styles/variables.scss";
.staff-manage {
  width: 100%;
  height: 100%;
  ::v-deep .el-form-item__content {
    display: flex;
    align-items: center;
  }
  ::v-deep .el-form-item__label {
    min-width: 100px;
  }
  ::v-deep .el-dialog {
    .el-dialog__body {
      height: 80%;
      overflow-y: auto;
      .el-form {
        height: 100%;
        display: flex;
        flex-wrap: wrap;
        overflow-y: auto;
      }
    }
  }
  .common-layout {
    border: 1px solid $borderColor;
    height: calc(100% - #{$actionBarHeight + 10});
    padding: 20px;
    .search-box {
      display: flex;
      align-items: center;
      .label-input {
        display: flex;
        align-items: center;
        .label {
          width: 100px;
          white-space: nowrap;
        }
      }
      .search {
        display: flex;
        align-items: center;
        img {
          height: 30px;
        }
      }
    }
    .content {
      height: calc(100% - 50px);
      margin: 20px 0;
      display: flex;
      .table-box {
        width: 50%;
        position: relative;
        height: 100%;
        overflow-y: auto;
      }
      .form {
        overflow-y: auto;
        width: 50%;
        height: 100%;
        padding-top: 20px;
        display: flex;
        justify-content: center;
        margin-left: 4%;
        border-left: dashed 1px $borderColor;
        .el-form {
          justify-content: center;
          width: 90%;
          flex-wrap: wrap;
        }
      }
    }
  }
}
</style>
